

from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from goods.models import SPU,GoodsCategory
from meiduo_admin.serializers.spu_serializers import *
from meiduo_admin.custom_page import MyPage
from meiduo_admin.serializers.sku_serializers import GoodsCategoryModelSerializer


# 返回一级分类
class SPUSimpleCategoryListView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = GoodsCategoryModelSerializer

    def get_queryset(self):
        # 如果请求路径中存在pk，那么返回根据pk过滤出的二级，三级分类
        p_id = self.kwargs.get('pk')
        if p_id:
            # 根据p_id过滤出子级
            return self.queryset.filter(parent_id=p_id)

        # 返回一级分类
        return self.queryset.filter(parent=None)



class BrandSimpleListView(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = BrandSimpleModelSerializer



class SPUModelViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUDetailModelSerializer
    pagination_class = MyPage

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if not keyword:
            return self.queryset.all()
        return self.queryset.filter(name__contains=keyword)